package com.by.common.swagger;

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@AutoConfiguration//定义当前类为自动配置类
@EnableConfigurationProperties(value = {SwaggerProperties.class}) //启用属性的批量绑定
@EnableOpenApi
public class SwaggerAutoConfiguration {

    SwaggerProperties properties;

    public SwaggerAutoConfiguration(SwaggerProperties properties) {
        this.properties = properties;
    }

    @Bean
    public Docket createDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(getApiInfo())
                .enable(properties.isEnable())
                .select()
                .apis(RequestHandlerSelectors.basePackage(properties.getBasePackage()))//控制类所在的包
                .paths(PathSelectors.ant(properties.getUrlPattern()))//扫描控制类中所有以/v1开头的路径
                .build();
    }

    private ApiInfo getApiInfo() {
        return new ApiInfoBuilder()
                .title(properties.getTitle())
                .description(properties.getDescription())
                .contact(new Contact(properties.getName(), properties.getUrl(), properties.getEmail()))
                .version(properties.getVersion())
                .build();
    }
}